<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use App\Job\ExceptionLogAddJob;
// use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Hyperf\HttpServer\Contract\RequestInterface;

class AppExceptionHandler extends ExceptionHandler
{
    // /**
    //  * @var StdoutLoggerInterface
    //  */
    // protected $logger;
    /**
     * @var RequestInterface
     */
    protected $request;

    public function __construct(RequestInterface $request)
    {
        // $this->logger = $logger;
        $this->request = $request;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // $this->logger->error(sprintf('%s [ %s ] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        // $this->logger->error($throwable->getTraceAsString());
        // 格式化输出
        $requestId = createId('RE');
        $data = json_encode([
            'code' => $throwable->getCode(),
            'data' => [],
            'request_id' => $requestId,
            'msg' => '内部服务异常'
        ], JSON_UNESCAPED_UNICODE);
        $logData['time'] = time();
        $logData['_id'] = $requestId;
        $logData['url'] = $this->request->fullUrl();
        $logData['file'] = $throwable->getFile() . ' ; Line: ' . $throwable->getLine();
        $logData['message'] = $throwable->getMessage();
        $logData['trace'] = $throwable->getTraceAsString();
        queue_push(new ExceptionLogAddJob($logData));
        unset($logData);
        return $response->withStatus(500)->withBody(new SwooleStream($data))->withHeader('Content-Type', 'application/json; charset=utf-8');;
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
